<template>
  <div class="chart-wrapper">
    <div class="filter-container">
      <el-select 
        v-model="selectedTitle" 
        placeholder="Please select the model" 
        @change="handleTitleChange"
        style="width: 300px; margin-bottom: 20px;"
        size='large'
      >
        <el-option
          label="All models"
          value="all"
        />
        <el-option
          v-for="title in uniqueTitles"
          :key="title"
          :label="title"
          :value="title"
        />
      </el-select>
    </div>
    <div class="scroll-container">
      <div class="chart-container">
        <div ref="chartRef" style="height: 500px;"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted, computed,watch } from 'vue';
  import axios from 'axios';
  import { ElMessage, ElSelect, ElOption } from 'element-plus';
  import * as echarts from 'echarts';
  import { useLoading } from '../../utils/loading';
  import { useSidebarStore } from '../../store/sidebarStore';
  const { showLoading, hideLoading } = useLoading();

  const BASE_URL = import.meta.env.VITE_API_URL;
  const chartRef = ref(null);
  const rawData = ref([]);
  const selectedTitle = ref('all'); // 默认选中"所有型号"
  const chartInstance = ref(null);
  const sidebarStore = useSidebarStore();
  const isCollapse = computed(() => sidebarStore.isCollapse);
  watch(isCollapse,async(newVal) => {
    await getNum();
  },{ flush: 'post' }) 
  // 获取所有唯一的title值
  const uniqueTitles = computed(() => {
    const titles = new Set();
    rawData.value.forEach(item => {
      if (item.title) titles.add(item.title);
    });
    return Array.from(titles);
  });

  // 根据选中的title筛选数据
  const filteredData = computed(() => {
    if (selectedTitle.value === 'all') return rawData.value;
    return rawData.value.filter(item => item.title === selectedTitle.value);
  });

  // 统计相同国家的数量
  const countCountries = (data) => {
    const countryCount = {};
    
    data.forEach(item => {
      const country = item.country || 'Unknown country';
      countryCount[country] = (countryCount[country] || 0) + 1;
    });
    
    // 转换为图表需要的格式
    const countries = Object.keys(countryCount);
    const counts = countries.map(country => countryCount[country]);
    
    return { countries, counts };
  };

  // 初始化图表
  const initChart = (data) => {
    if (!chartRef.value) return;
    
    // 销毁旧实例
    if (chartInstance.value) {
      chartInstance.value.dispose();
    }
    
    // 创建新实例
    chartInstance.value = echarts.init(chartRef.value);
    
    // 统计国家数量
    const { countries, counts } = countCountries(data);
  
    // 图表配置
    const option = {
      title: {
        text: selectedTitle.value === 'all' ? 'User distribution of all models' : `${selectedTitle.value} user distribution`,
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        axisPointer: {
          type: 'shadow'
        },
        formatter: '{b}: {c}person'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: countries,
        axisLabel: {
          rotate: countries.some(name => name.length > 4) ? 30 : 0,
          interval: 0,
        },
        axisTick: {
          alignWithLabel: true
        },
        // 左对齐关键配置
        axisLine: {
          onZero: false
        },
        boundaryGap: true
      },
      yAxis: {
        type: 'value',
        name: 'Number of people'
      },
      
      series: [{
        name: 'Number of people',
        type: 'bar',
        barWidth: '60%',
        barGap: '20', // 柱子间间距
        barCategoryGap: '0', // 类目间柱形间距
        data: counts,
        // 左对齐关键配置
        barMinHeight: 5, // 最小高度
        itemStyle: {
          color: function(params) {
            // 使用渐变色
            const colors = [
              '#FF0000', '#FFA500', '#FFFF00', '#008000', '#0000FF', '#4B0082', '#FF00FF'
            ];
            return colors[params.dataIndex % colors.length];
          },
          borderRadius: [5, 5, 0, 0]
        },
        label: {
          show: true,
          position: 'top'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }],
      
    };
    
    // 设置配置项
    chartInstance.value.setOption(option);
    
    // 响应式调整
    window.addEventListener('resize', function() {
      chartInstance.value && chartInstance.value.resize();
    });
  };

  // 处理选择变化
  const handleTitleChange = () => {
    initChart(filteredData.value);
  };

  // 获取数据
  const getNum = async () => {
    showLoading('loading...')
    try {
      const res = await axios.get(`${BASE_URL}manage/countControllerModel`);
      
      if (Array.isArray(res.data.data)) {
        rawData.value = [...res.data.data];
        initChart(filteredData.value);
      } else {
        ElMessage.warning('The returned data is not in array format');
      }
    } catch (error) {
      ElMessage.error(`${error.msg}`);
    } finally {
      hideLoading();
    }
  };

  onMounted(() => {
    getNum();
  });
</script>

<style scoped>
  .chart-wrapper {
    width: 100%;
  }

  .filter-container {
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
  }

  /* 新增滚动容器样式 */
  .scroll-container {
    width: 100%;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    padding: 20px;
    box-sizing: border-box;
  }

  .chart-container {
    height: 500px;
  }
</style>